const sqlite3 = require('sqlite3').verbose();
const path = require('path');

// 数据库路径
const dbPath = path.join(__dirname, 'database.db');

// 连接数据库
const db = new sqlite3.Database(dbPath, (err) => {
  if (err) {
    console.error('Error opening database:', err.message);
    return;
  }
  console.log('Connected to SQLite database.');
});

// 苏州配置数据
const suzhouConfigs = [
  {
    sequence_number: 1,
    start_addr: '1000',
    data_type: '4', // 32位浮点数
    variable: 'suzhou.detection_limit',
    description: '检出限',
    note: '苏州卫水动态管控协议'
  },
  {
    sequence_number: 2,
    start_addr: '1002',
    data_type: '4', // 32位浮点数
    variable: 'suzhou.zero_calibration_deviation',
    description: '零点校准浓度允许偏差值',
    note: '苏州卫水动态管控协议'
  },
  {
    sequence_number: 3,
    start_addr: '1004',
    data_type: '4', // 32位浮点数
    variable: 'suzhou.zero_calibration_measured',
    description: '零点校准浓度测量值',
    note: '苏州卫水动态管控协议'
  },
  {
    sequence_number: 4,
    start_addr: '1006',
    data_type: '4', // 32位浮点数
    variable: 'suzhou.zero_calibration_error',
    description: '零点校准测量偏差',
    note: '苏州卫水动态管控协议'
  },
  {
    sequence_number: 5,
    start_addr: '1008',
    data_type: '4', // 32位浮点数
    variable: 'suzhou.range_calibration_deviation',
    description: '量程校准浓度允许偏差值',
    note: '苏州卫水动态管控协议'
  },
  {
    sequence_number: 6,
    start_addr: '1010',
    data_type: '4', // 32位浮点数
    variable: 'suzhou.range_calibration_measured',
    description: '量程校准浓度测量值',
    note: '苏州卫水动态管控协议'
  },
  {
    sequence_number: 7,
    start_addr: '1012',
    data_type: '4', // 32位浮点数
    variable: 'suzhou.range_calibration_error',
    description: '量程校准测量偏差',
    note: '苏州卫水动态管控协议'
  },
  {
    sequence_number: 8,
    start_addr: '1014',
    data_type: '4', // 32位浮点数
    variable: 'suzhou.standard_check_deviation',
    description: '标液核查浓度允许偏差值',
    note: '苏州卫水动态管控协议'
  },
  {
    sequence_number: 9,
    start_addr: '1020',
    data_type: '2', // 16位无符号整数
    variable: 'suzhou.main_status',
    description: '主状态',
    note: '苏州卫水动态管控协议'
  },
  {
    sequence_number: 10,
    start_addr: '1021',
    data_type: '2', // 16位无符号整数
    variable: 'suzhou.sub_status',
    description: '子状态（运行状态）',
    note: '苏州卫水动态管控协议'
  },
  {
    sequence_number: 11,
    start_addr: '1022',
    data_type: '2', // 16位无符号整数
    variable: 'suzhou.test_sample_mark',
    description: '测试样品标记',
    note: '苏州卫水动态管控协议'
  },
  {
    sequence_number: 12,
    start_addr: '1023',
    data_type: '2', // 16位无符号整数
    variable: 'suzhou.test_result_mark',
    description: '测试结果标记',
    note: '苏州卫水动态管控协议'
  }
];

// 添加苏州配置数据
function addSuzhouConfigs() {
  console.log('正在添加苏州配置数据...');
  
  // 首先清除现有的1000+地址的记录
  db.run(
    `DELETE FROM config_data WHERE CAST(start_addr AS INTEGER) >= 1000`,
    function(err) {
      if (err) {
        console.error('清除现有记录失败:', err.message);
        return;
      }
      
      console.log(`已清除 ${this.changes} 条现有记录`);
      
      // 插入新的苏州配置
      const insertPromises = suzhouConfigs.map((config) => {
        return new Promise((resolve, reject) => {
          db.run(
            `INSERT INTO config_data (sequence_number, start_addr, data_type, variable, description, note)
             VALUES (?, ?, ?, ?, ?, ?)`,
            [config.sequence_number, config.start_addr, config.data_type, config.variable, config.description, config.note],
            function(err) {
              if (err) {
                reject(err);
              } else {
                console.log(`已添加: ${config.description} (地址: ${config.start_addr})`);
                resolve();
              }
            }
          );
        });
      });
      
      // 等待所有插入完成
      Promise.all(insertPromises)
        .then(() => {
          console.log('\n所有苏州配置添加完成，查看结果:');
          
          // 查看添加后的数据
          db.all(
            `SELECT id, sequence_number, start_addr, data_type, variable, description, note 
             FROM config_data 
             WHERE CAST(start_addr AS INTEGER) >= 1000 
             ORDER BY CAST(start_addr AS INTEGER)`,
            (err, rows) => {
              if (err) {
                console.error('查询结果失败:', err.message);
              } else {
                console.table(rows);
                console.log(`\n成功添加了 ${rows.length} 条苏州配置记录`);
              }
              
              db.close((err) => {
                if (err) {
                  console.error('关闭数据库失败:', err.message);
                } else {
                  console.log('数据库连接已关闭');
                }
              });
            }
          );
        })
        .catch((err) => {
          console.error('添加配置失败:', err.message);
          db.close();
        });
    }
  );
}

// 执行添加
addSuzhouConfigs();